package com.thinkcube.edutainment.fragment;

import java.util.ArrayList;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Trace;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.thinkcube.edutainment.EdutainmentConstant;
import com.thinkcube.edutainment.R;
import com.thinkcube.edutainment.ReachabilityTest;
import com.thinkcube.edutainment.adapters.LessonBarAdapter;
import com.thinkcube.edutainment.client.LessonClient;
import com.thinkcube.edutainment.client.UserClient;
import com.thinkcube.edutainment.domain.Lesson;
import com.thinkcube.edutainment.domain.OAuth;
import com.thinkcube.edutainment.domain.data.CourseData;
import com.thinkcube.edutainment.domain.data.LessonData;
import com.thinkcube.edutainment.domain.dto.CourseDto;
import com.thinkcube.edutainment.domain.dto.OAuthDto;

@EFragment(R.layout.follow__course_lesson_bar)
public class FollowCourseLessonBar extends Fragment implements OnItemClickListener {

	@ViewById(R.id.list)
	ListView listview;

	@RestService
	LessonClient lessonClient;

	@RestService
	UserClient userClient;

	@Bean
	CourseDto courseDto;
	@Bean
	OAuthDto oAuthDto;

	private ArrayList<LessonData> lessonsList;

	CourseData courseData = new CourseData();

	int selectedPosition;

	@AfterViews
	void initUi() {

		if (getArguments().containsKey("pos")) {
			selectedPosition = getArguments().getInt("pos");
		}

		if (getArguments().containsKey("course")) {

			courseData = getArguments().getParcelable("course");

		}

		gettoken();

	}

	@Background
	void gettoken() {
		oAuthDto.setAppId(EdutainmentConstant.APP_ID);
		oAuthDto.setAppSecret(EdutainmentConstant.APP_SCRET);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					setTokenUi(userClient.getRequestToken(oAuthDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});

	}

	@UiThread
	void showMessge(final String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
	}

	void setTokenUi(OAuth requestToken) {

		getLesson(requestToken);
	}

	@Trace
	@Background
	void getLesson(OAuth requestToken) {

		courseDto.setAuthToken(requestToken.getoAuth().getToken());

		courseDto.setCourseId(courseData.getCourseId());

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					doUi(lessonClient.getLesson(courseDto.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("Not Connected ");
			}
		});

	}
	
	
	LessonBarAdapter ladapter;

	@UiThread
	void doUi(Lesson lesson) {
		
		if(lesson.getLessonList()!=null)
		{
	
			listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	
			ladapter = new LessonBarAdapter(getActivity(),
					new String[lesson.getLessonList().size()],
					(ArrayList<LessonData>) lesson.getLessonList(),
					selectedPosition);
			listview.setAdapter(ladapter);
	
			lessonsList = (ArrayList<LessonData>) lesson.getLessonList();
	
			listview.setOnItemClickListener(this);
		}

	}
	
	
	
	private void accessLesson(LessonBarAdapter adapter,int position)
	{
		if((lessonsList!=null)&&(lessonsList.size()>0))
		{
			LessonData lessonItem = lessonsList.get(position);
			adapter.setSelectedItem(position);
	
			FragmentTransaction fragmentTransaction = getFragmentManager()
					.beginTransaction();
			Bundle bundle = new Bundle();
			FollowCoureseDetail lessonLontent = new FollowCoureseDetail_();
			bundle.putParcelable("lessonContents", lessonItem);
			lessonLontent.setArguments(bundle);
	
			fragmentTransaction.replace(R.id.lesson_content, lessonLontent);
			fragmentTransaction.addToBackStack(null);
			fragmentTransaction.commit();
	    }
	}
	
	
	
	

	@Click({ R.id.forum, R.id.wiki, R.id.glossary })
	public void onClick(View v) {
		
		
		FragmentTransaction fragmentTransaction = getFragmentManager()
				.beginTransaction();
		switch (v.getId()) {
		case R.id.forum:
			
			
			ForumListFragment forumFragment=new ForumListFragment_();
			Bundle fbundle=new Bundle();
			fbundle.putParcelable("Course", courseData);
			forumFragment.setArguments(fbundle);
			fragmentTransaction.replace(R.id.lesson_content, forumFragment);
			fragmentTransaction.addToBackStack(null);
			fragmentTransaction.commit();
			
			break;
		case R.id.wiki:
			
			WikiFragment wikiFragment=new WikiFragment_();
			Bundle bundle1=new Bundle();
			bundle1.putParcelable("Course", courseData);
			wikiFragment.setArguments(bundle1);
			fragmentTransaction.replace(R.id.lesson_content, wikiFragment);
			fragmentTransaction.addToBackStack(null);
			fragmentTransaction.commit();
			
			break;

		case R.id.glossary:
			
			GlossaryFragment glossaryFragment=new GlossaryFragment_();
			Bundle bundle=new Bundle();
			bundle.putParcelable("Course", courseData);
			glossaryFragment.setArguments(bundle);
			fragmentTransaction.replace(R.id.lesson_content, glossaryFragment);
			fragmentTransaction.addToBackStack(null);
			fragmentTransaction.commit();
			
			break;

		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> aradapter, View view, int position, long id) {
		
		int type=  Integer.valueOf(lessonsList.get(position).getLessonType());
		switch (type) {
		case 0:
			
				accessLesson(ladapter,position);
			
			break;
			
		case 1:
			
				if(courseData.getIsCoursePurchased()!=null)
				{
					if((courseData.getIsCoursePurchased().equals("true"))||
							(lessonsList.get(position).getIs_lesson_purchased().equals("true")))
					{
						accessLesson(ladapter,position);
					}
					else
					{
						showMessge(getString(R.string.lesson_access));
					}
				}
			
			break;
			
		case 2:
			
				if(lessonsList.get(position).getIs_lesson_purchased().equals("true"))
				{
					accessLesson(ladapter,position);
				}
				else{
					
					showMessge(getString(R.string.lesson_access));
				}
			
			break;

		default:
			break;
		}
		
	}

}
